import {getRequest} from "./api";
import router from "../router";

/**
 * @name:
 * @description: 菜单格式化
 * @author: 皮蛋布丁
 * @date: 2021-05-13 22:33:12
 */
export const initMenu=(router,store)=> {
    //有请求数据
    if (store.state.routes.length > 0) {
        return;
    }

    getRequest("/system/config/menu").then(data=> {
        //请求到数据
        if (data) {
            let fmtRoutes = formatRoutes(data);
            router.addRoutes(fmtRoutes);
            //初始化utils/index.js中的state.routes:[]
            store.commit('initRoutes',fmtRoutes);
            store.dispatch('connect');
        }
    })
}

export const formatRoutes=(routes)=> {
    //返回的数据
    let fmRoutes = [];
    routes.forEach(router=> {
        //批量的变量定义，赋值给router
        let {
            path,
            component,
            name,
            meta,
            iconCls,
            children
        } = router;
        //存在且为数组
        if (children && children instanceof Array) {
            children = formatRoutes(children);
        }
        let fmRouter = {
            path:path,
            name:name,
            iconCls:iconCls,
            meta:meta,
            children:children,
            //动态加载component
            component(resolve) {
                if (component.startsWith('Home')) {
                    //动态导入包(router中的index.js)
                    require(['../views/' + component + '.vue'],resolve);
                }else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'],resolve);
                }else if (component.startsWith('Per')) {
                    require(['../views/per/' + component + '.vue'],resolve);
                }else if (component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'],resolve);
                }else if (component.startsWith('Sta')) {
                    require(['../views/sta/' + component + '.vue'],resolve);
                }else if (component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'],resolve);
                }

                //动态导入包(router中的index.js)
                require(['../views/' + component + '.vue'],resolve);

            }
        }
        fmRoutes.push(fmRouter);
    })
    return fmRoutes;
}